﻿using ca2simulator.shared;

namespace ca2simulator.client.model.transfer
{
    public class BasicLifeTransfer : ITransferFunc
    {

        public CellState NextState(Lattice lattice, int r, int c)
        {
            CellState state;
            CellState curState = lattice[r,c].CellState;
            state.State=curState.State;

            int liveCnt=0;
            int maxRow = lattice.Rows;
            int maxCol = lattice.Columns;

            for(int i=-1;i<2;i++)
            {
                for(int j=-1;j<2;j++)
                {
                    //Break if out of bounds, no wrapping here!
                    if (r + i < 0) r += maxRow;
                    if (r + i >= maxRow) r -= maxRow;

                    if (c + j < 0) c += maxCol;
                    if(c+j>=maxCol) c-=maxCol;
                    // Don't let cell count itself
                    if (i == 0 && j == 0) continue;
                    
                    // count the number of living cells
                    //if (lattice[r + i, c + j].CellState.State == 1) liveCnt++;
                    if (lattice._Cells[(r + i) * 800 + (c + j)].CellState.State == 1) liveCnt++;
                }
            }
            if (curState.State == 1)
            {
                if (liveCnt < 2) state.State = 0;
                else if (liveCnt > 3) state.State = 0;
            }
            else
            {
                if (liveCnt == 3) state.State =0;
            }
            return state;
        }

    }
}
